package cn.net.xyan.text.listener


import org.jnativehook.keyboard.NativeKeyEvent
import org.jnativehook.keyboard.NativeKeyListener
import  org.jnativehook.NativeInputEvent.*
import java.awt.Robot
import java.awt.event.KeyEvent

fun NativeKeyEvent.hasModifier(code:Int):Boolean{
    return (this.modifiers and code) != 0
}

fun NativeKeyEvent.hasCTRL():Boolean{
    return hasModifier(CTRL_MASK)
}

fun NativeKeyEvent.hasSHIFT():Boolean{
    return hasModifier(SHIFT_MASK)
}

fun NativeKeyEvent.hasALT():Boolean{
    return hasModifier(ALT_MASK)
}

fun NativeKeyEvent.hasMETA():Boolean{
    return hasModifier(META_MASK)
}

val NativeKeyEvent.keyText:String get() {
    val str =   NativeKeyEvent.getKeyText(this.keyCode)

    return str
}

class SendKeyJob(val keys:IntArray){
    var runFlag:Boolean = false

    var started:Boolean
        get() { return runFlag}
        set(value) {
            if (value && !runFlag) start()
            else {
                if (!value) stop()
            }}
    private var robot = Robot()
    private var thread:Thread? = null

    fun start(){
        println("start")
        runFlag = true
        thread = Thread({
            while (runFlag){
                robot.delay(100)

                keys.forEach {
                    robot.keyPress(it)
                }

                keys.reverse()

                keys.forEach { robot.keyRelease(it) }

                keys.reverse()
            }
        })

        thread!!.start()
    }

    fun stop(){
        println("stop")
        runFlag = false
    }
}

class KeyboardListener:NativeKeyListener{

    val job1 = SendKeyJob(intArrayOf(KeyEvent.VK_1))
    val job2 = SendKeyJob(intArrayOf(KeyEvent.VK_2))
    override fun nativeKeyReleased(e: NativeKeyEvent?) {
        println(e!!.paramString())
        if (e!!.keyText == "F") {

            job1.started = false
        }

        else if (e!!.keyText == "R") {

            job2.started = false
        }
    }

    override fun nativeKeyPressed(e: NativeKeyEvent?) {
        println(e!!.paramString())
        if (e!!.keyText == "F") {

            job1.started = true
        }

        else if (e!!.keyText == "R") {

            job2.started = true
        }
        //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun nativeKeyTyped(e: NativeKeyEvent?) {
        println(e!!.paramString())
//        //TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
//        println(e.keyText)
//        if (e.keyChar == 'f') {
//
//            job1.started = !job1.started
//        }
//
//        else if (e.keyChar == 'g') {
//
//            job2.started = !job2.started
//        }
    }

}